const router = require('express').Router()
const { chkToken } = require('../../util')
const {query} = require('../../db')
const moment = require('moment')

const tableName = 'gifts'

router.get('/my', chkToken, async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20

    let offset = (page-1)*pageSize
    let sql = `SELECT b.id,b.gift_name,b.gift_icon,a.price,a.addtime,c.name
                FROM user_gifts a
                 LEFT JOIN gifts b ON a.gift_id=b.id
                 LEFT JOIN users c ON a.from_id=c.id
                 WHERE a.to_id=? 
                LIMIT ${offset},${pageSize}`

    let data = await query(sql, req.userId).catch(next)
    if(data === undefined) return

    let total = await query(`SELECT COUNT(*) total FROM user_gifts WHERE to_id=?`, req.userId).catch(next)
    if(total === undefined) return

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.get('/isend', chkToken, async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20

    let offset = (page-1)*pageSize
    let sql = `SELECT b.id,b.gift_name,b.gift_icon,a.price,a.addtime,c.name
                FROM user_gifts a
                 LEFT JOIN gifts b ON a.gift_id=b.id
                 LEFT JOIN users c ON a.to_id=c.id
                 WHERE a.from_id=? 
                LIMIT ${offset},${pageSize}`

    let data = await query(sql, req.userId).catch(next)
    if(data === undefined) return

    let total = await query(`SELECT COUNT(*) total FROM user_gifts WHERE from_id=?`, req.userId).catch(next)
    if(total === undefined) return

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.get('/', async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20

    let offset = (page-1)*pageSize
    let sql = `SELECT * FROM ${tableName} LIMIT ${offset},${pageSize}`

    let data = await query(sql).catch(next)
    if(data === undefined) return

    let total = await query(`SELECT COUNT(*) total FROM ${tableName}`).catch(next)
    if(total === undefined) return

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.post('/give', chkToken, async (req, res, next) => {
    let user_id = req.body.user_id // 主播ID
    let gift_id = req.body.gift_id  // 礼物ID

    // 获取礼物价格
    let giftInfo = await query('SELECT price FROM gifts WHERE id = ?', gift_id).catch(next)
    if(giftInfo === undefined) return

    // 获取用户余额
    let userInfo = await query('SELECT money FROM users WHERE id = ?', req.userId).catch(next)
    if(userInfo === undefined) return

    if(giftInfo.length === 0) {
        res.json({
            'ok': 0,
            'error': '礼物不存在'
        })
        return 
    }

    if(giftInfo[0].price > userInfo[0].money) {
        res.json({
            'ok': 0,
            'error': '余额不足'
        })
        return 
    }

    let body = {
        from_id: req.userId,
        to_id: user_id,
        gift_id,
        addtime: moment().unix(),
        price: giftInfo[0].price
    }

    await query('START TRANSACTION')

    let total = await query(`INSERT INTO user_gifts SET ?`, body).catch(next)
    if(total === undefined) {
        await query('ROLLBACK')
        return
    }

    let ret = await query('UPDATE users SET money=money-? WHERE id = ?', [giftInfo[0].price, req.userId]).catch(next)
    if(ret === undefined) {
        await query('ROLLBACK')
        return
    }

    let ret1 = await query('UPDATE users SET money=money+? WHERE id = ?', [giftInfo[0].price, user_id]).catch(next)
    if(ret1 === undefined) {
        await query('ROLLBACK')
        return
    }

    await query('COMMIT')

    res.json({
        'ok': 1
    })
})

module.exports = router